var table;
var idxMap = new Map();
var authtree
    , $
    , form
    , layer
    , currentTreeNode
    , resultData
    , valueMap = new Map();
const storageValue = "roleUserTableWidths";

layui.config({
    base: '/static/lib/layuiadmin/',
}).extend({
    authtree_zimi: 'modules/authtree_zimi',
}).use(['table', 'jquery', 'form', 'layer', 'authtree_zimi'], function () {
    $ = layui.jquery;
    form = layui.form;
    layer = layui.layer;
    authtree = layui.authtree_zimi;
    table = layui.table;

    var widths = localStorage[storageValue] ? JSON.parse(localStorage[storageValue]) : [160];

    table.render({
        id: 'sysRoleLoad'
        , elem: '#test'
        , url: '/sys-role/list'
        , method: 'post'
        , cellMinWidth: 80 //全局定义常规单元格的最小宽度，layui 2.2.1 新增
        , even: true//隔行变色
        , limits: [10, 20, 30, 50, 80, 100]//每页条数的选择项，默认：[10,20,30,50,80,100]。
        , limit: 10//每页显示的条数（默认：10）
        , height: 650
        , width: 380
        , request: {}
        , where: {roleState: 1}
        , cols: [[
            {field: 'id', width: 160, title: 'ID', align: 'left', sort: true}
            , {field: 'roleName', title: '角色名', align: 'left'}
        ]]
        , page: true
        , done: function (res, curr, count) {
            idxMap.clear();

            resultData = res.data;

            for (var i = 0; i < resultData.length; i++) {
                idxMap.set(resultData[i].id, resultData[i]);
            }
        }
    });

    //监听行单击事件（单击事件为：rowDouble）
    table.on('row(test)', function (obj) {
        $(".roleNameText").html(`给<span style="color: #F72E29">${obj.data.roleName}</span>角色添加以下成员`);

        load_user_tree(obj.data.id);
    });

    $('th').mouseup(function () {
        var tr = $(this).parent()["0"];
        var widths = [];
        for (var i = 0; i < tr.cells.length - 1; i++) {
            widths.push(tr.cells[i].clientWidth);
        }

        localStorage[storageValue] = JSON.stringify(widths);
    });
});


/*
* @author: wj
* @description: 加载人员树
* @date: 2019/1/17 16:25
* @param
* @return
*/
function load_user_tree(roleId) {
    $.ajax({
        url: '/sys-role-user/getOrgPostUser'
        , type: 'post'
        , data: {roleId: roleId}
        , success: function (res) {
            if (res.code == 0) {
                var trees = formatData(res.data, 'parentId', 'id', 'name', 'choiceFlag');
                authtree.render('#orgTree', trees, {
                    inputname: 'authids[]',
                    layfilter: 'lay-check-auth',
                    fgo: 0,
                    checkedArr: res.checkedArr,
                    flags: [5],
                    autowidth: true,
                });

                authtree.on('change(lay-check-auth)', function (data) {
                    // 获取所有已选中节点
                    var lastChecked = authtree.lastCheckedNode['#orgTree'] //获取最新选中
                        , lastNotChecked = authtree.lastNotCheckedNode['#orgTree'] // 获取最新取消
                        , checkedNode = authtree.checkedNode['#orgTree'] //获取最新选中
                        , notCheckedNode = authtree.notCheckedNode['#orgTree'] //获取最新选中
                        , url
                        , value
                        , values = [];

                    if (lastChecked.length > 0) {
                        value = eval("(" + lastChecked[0] + ")");
                        value.roleId = roleId;
                        url = "/sys-role-user/saveRoleUser";
                    } else {
                        value = eval("(" + lastNotChecked[0] + ")");
                        value.roleId = roleId;
                        url = "/sys-role-user/deleteRoleUser";
                    }

                    // 向服务器发出Ajax请求
                    $.ajax({
                        async: false,
                        type: 'post',
                        dataType: "json",
                        url: url,
                        data: value,
                        contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
                        timeout: 30000,//超时时间设置为1分钟；
                        success: function (data) {
                            if (data.code == 0) {
                                layer.msg("提交成功!", {icon: 1, time: 1000});
                            } else {
                                layer.msg(data.msg, {icon: 1, time: 1000});
                            }
                        },
                        complete: function (XMLHttpRequest, textStatus) {
                            refresh(roleId);

                        },
                        error: function (a, b, c) {
                            // 请求出错处理,依然初始化咨询节点信息
                            if (b == 'timeout') {
                                layer.alert("请求超时，请再次尝试！", {title: '错误信息：'});
                            } else {
                                layer.alert(url + "请求异常", {title: '错误信息：'});
                            }
                        }
                    });

                });

                authtree.showDept('#orgTree', 2);
            } else {
                layer.msg(data.msg, {icon: 5, time: 1000});
            }

        }
    });
}

function refresh(roleId) {
    load_user_tree(roleId);
}


/**
 * 数据封装
 * @param data 数据
 * @param pid  父ID
 * @param id  ID
 * @param name 显示名称
 * @param checked 选中状态
 */
function formatData(values, pid, id, name, checked) {
    //转换flag
    values.map(item =>{
        item.flag = changeFlag(item.flag);
    });

    var tree = [],
        item,
        obj;

    var orgMap = new Map();
    var postMap = new Map();
    var userMap = new Map();
    var cateMap = new Map();

    // 1)变格式保存到Map
    for (var i = 0; i < values.length; i++) {

        item = new Object();

        obj = valueMap.get(`${values[i].flag}-${values[i].orgId}-${values[i].id}`)
        if (!obj && values[i].id) obj = valueMap.get(`${values[i].flag}-0-${values[i].id}`)

        if (obj) {
            values[i][checked] = true;
        }

        item.value = JSON.stringify(values[i]).replace(/"/g, "'");
        item.name = values[i][name];
        item.type = values[i].flag;
        item.checked = values[i][checked];
        item.list = [];

        switch (values[i].flag) {
            case 1:
                item.name = values[i].orgName;
                cateMap.set(values[i].orgId, item);
                tree.push(item);
                break;
            case 2:
                orgMap.set(values[i][id], item);
                break;
            case 3:
                postMap.set(values[i].orgId + '-' + values[i][id], item);
                break;
            case 4:
                userMap.set(values[i][id], item);
                break;
        }
    }

    // 2)作为子项目加到父项目的list
    for (var i = 0; i < values.length; i++) {
        switch (values[i].flag) {
            case 1:
                break;
            case 2:
                if (values[i][pid] > 0) {
                    obj = orgMap.get(values[i][pid]);
                } else {
                    obj = cateMap.get(values[i].orgCateId);
                }

                obj.list.push(orgMap.get(values[i][id]));

                break;
            case 3:
                obj = orgMap.get(values[i][pid]);
                obj.list.splice(obj.list.length - 1, 0, postMap.get(values[i].orgId + '-' + values[i][id]));
                break;
            case 4:
                obj = postMap.get(values[i].orgId + '-' + values[i].postId);

                if (obj) {
                    obj.list.push(userMap.get(values[i][id]));
                }
                break;
        }
    }

    // 3)删除没有子项目的list
    for (var i = 0; i < tree.length; i++) {
        removeChild(tree[i]);
    }

    return tree;
}

function changeFlag(flag) {
    switch (flag) {
        case 0:
            flag = 1;
            break;
        case 1:
            flag = 2;
            break;
        case 5:
            flag = 4;
            break;
    }
    return flag ;
}

function removeChild(obj) {
    if (obj.hasOwnProperty('list')) {
        if (obj.list.length > 0) {
            if (obj.list.length == 1 && obj.type == 1) {
                delete obj.list;
            } else {
                for (var i = obj.list.length - 1; i >= 0; i--) {
                    removeChild(obj.list[i]);
                }
            }
        } else {
            delete obj.list;
        }
    }
}